import { reqWXConfig } from '@/lib/api';

import {
	Toast
  } from 'vant'
const wxSdk = {
    isAndroid: function(){
		return window.navigator.appVersion.toLowerCase().indexOf('android') != -1;
	},
	isIOS: function(){
		return window.navigator.appVersion.toLowerCase().indexOf('iphone') != -1;
	},
	isWeiXinWeb: function () {
		var ua = window.navigator.userAgent.toLowerCase();
		return ua.match(/MicroMessenger/i) == 'micromessenger';
    },

    wxReadyIsLoading: false,
	wxReadyCallbacks: [],
    wxReadyData: null,
    
    wxReady: function (call,url) {
		var me = this;
		if(call && me.wxReadyData ){
			call();
			return;
		}
		if(me.wxReadyIsLoading){
			me.wxReadyCallbacks.push(call);
			return;
		}
		me.wxReadyIsLoading = true;
		if(!url) {
			return
		}
		console.log('url---',url);
		reqWXConfig({
			// url: store.state.config.URL_SDK + 'wap/festivalActivity/redirect.html'
			url: url,
		}).then( (res) => {
			var wxJs = {};
			if(res.success) {
				wxJs = Object.assign( {}, {
					appId: res.d.wechatSet.appId,
					timestamp: res.d.timestamp,
					nonceStr: res.d.nonceStr,
					signature: res.d.signature,
				})
				wxJs.jsApiList = [
					'onMenuShareTimeline',
					'onMenuShareAppMessage',
					'updateTimelineShareData',
					'updateAppMessageShareData',
					'scanQRCode', 
					'getLocation', 
					'openLocation',
					'getNetworkType',
					'openBusinessView',
					'hideMenuItems',
					'showMenuItems',
				];
				wxJs.debug = false;
				console.log('wxJs----',wxJs)
				wx.config(wxJs);
				wx.ready(function () {
					me.wxReadyIsLoading = false;
					me.wxReadyData = wxJs;
					if( call ){
						call();
					}
					for(var i=0; i<me.wxReadyCallbacks.length; i++){
						if( me.wxReadyCallbacks[i] ){
							me.wxReadyCallbacks[i]();
						}
					}
					me.wxReadyCallbacks = [];
				});
				wx.error(function(res){
					console.log('wx.config error --- ', res);
					Toast({
						message: '微信js-sdk出错了' + JSON.stringify(res),
						position: 'top',
					});
				});
			}
		})
		
	},
}

export default {
    wxSdk
}